﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;

namespace Axa.CasinoApp.Client.ProcessLayer.WebRequest
{
    public class AsyncWebRequestHandler
    {
        #region Members

        /// <summary>
        /// Event der ausgelöst wird, sobald der Request asynchron beendet wurde.
        /// </summary>
        public event EventHandler<ResponseEventArgs> RequestCompleted;

        /// <summary>
        /// XML Nachricht die gesendet wird.
        /// </summary>
        private string _envelope = string.Empty;

        #endregion Members

        #region Ctor

        /// <summary>
        /// Erstellt eine neue Instanz. Achtung, für jeden Aufruf muss eine neue Instanz erstellt werden.
        /// </summary>
        /// <param name="envelope">XML Nachricht die gesendet wird.</param>
        public AsyncWebRequestHandler(string envelope)
        {
            _envelope = envelope;
        }

        #endregion Ctor

        /// <summary>
        /// Startet den asynchronen WebRequest.
        /// </summary>
        public void BeginRequestAsync(string url)
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp(url);
            request.ContentType = "text/xml; charset=UTF-8";
            request.Method = "POST";
            request.BeginGetRequestStream(doRequest, request);
        }

        private void doRequest(IAsyncResult asyncResult)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            Stream _body = request.EndGetRequestStream(asyncResult);

            byte[] formBytes = encoding.GetBytes(_envelope);

            _body.Write(formBytes, 0, formBytes.Length);
            _body.Close();

            request.BeginGetResponse(SearchResponseCallback, request);
        }

        private void SearchResponseCallback(IAsyncResult asyncResult)
        {
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
            Stream content = response.GetResponseStream();

            if (request != null && response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader reader = new StreamReader(content))
                    {
                        string responseString = reader.ReadToEnd();
                        reader.Close();
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            OnRequestCompleted(new ResponseEventArgs(responseString));
                        });
                        return;
                    }
                }
            }
            OnRequestCompleted(new ResponseEventArgs(null));
        }

        private void OnRequestCompleted(ResponseEventArgs e)
        {
            EventHandler<ResponseEventArgs> handler = RequestCompleted;

            if (handler != null)
            {
                handler(this, e);
            }
        }
    }
}
